package com.lhl.netty.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Administrator on 2016/4/28.
 */
public class NetEncoder extends ChannelOutboundHandlerAdapter {
    private final static Logger logger = LoggerFactory.getLogger(NetEncoder.class);

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
        try{
            NetMessage m = (NetMessage) msg;
            byte[] data = m.toBytes();
            ByteBuf encoded = ctx.alloc().buffer(data.length);
            encoded.writeBytes(data);
            ctx.write(encoded, promise); // (1)
        }catch(Exception e){
            logger.error(ExceptionUtil.getMessage(e));
        }
    }
}